﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;

using System.Net;

namespace client
{
    public partial class Form1 : Form
    {
        Socket clientSocket;
        Thread clientThread;

        public Form1()
        {
            InitializeComponent();
        }

        private void btconnect_Click(object sender, EventArgs e)
        {
            clientThread = new Thread(new ThreadStart(ConnectToServer));
            clientThread.Start();

        }

        private void btexit_Click(object sender, EventArgs e)
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
            Application.Exit();
        }

        private void ConnectToServer()
        {
            byte[] data = new byte[1024];

            //创建一个套接字
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.6.126"), 1234);
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //将套接字与远程服务器地址相连
            try
            {
                clientSocket.Connect(ipep);
            }
            catch (SocketException ex)
            {
                MessageBox.Show("连接错误: " + ex.Message);
                return;
            }

            while (true)
            {
                //接收服务器信息
                int bufLen = 0;
                try
                {
                    bufLen = clientSocket.Available;

                    clientSocket.Receive(data, 0, bufLen, SocketFlags.None);
                    if (bufLen == 0)
                    {
                        continue;
                    }
                }
                catch (SocketException ex)
                {
                    if (ex.NativeErrorCode.Equals(10035))
                        MessageBox.Show("处于连接中，但是发送数据 阻塞中");
                    else
                        MessageBox.Show("已关闭Socket连接");
                    //MessageBox.Show("接受数据出错:" + ex.Message);
                    return;
                }

                string clientcommand = System.Text.Encoding.Unicode.GetString(data).Substring(0, bufLen);

                lstClient.Items.Add(clientcommand); //接收来自至服务器端的数据

                //clientSocket.Shutdown(SocketShutdown.Both);
                //clientSocket.Close();
            }
        }

        private void btsend_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            data = Encoding.Unicode.GetBytes(txtClient.Text);
            clientSocket.Send(data, data.Length, SocketFlags.None);
            lstClient.Items.Add(Encoding.Unicode.GetString(data));
            
        }


    }
}